package com.aceitunaproject.server.player;

import java.util.Properties;
import java.util.logging.Logger;


import com.sun.corba.se.impl.util.Version;
import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ClientSession;
import com.sun.sgs.app.DataManager;
import com.sun.sgs.app.NameNotBoundException;
import com.sun.sgs.impl.sharedutil.LoggerWrapper;
import com.sun.sgs.impl.util.AbstractService;
import com.sun.sgs.kernel.ComponentRegistry;
import com.sun.sgs.service.TransactionProxy;

/**
 * Player service implementation
 * 
 * @author Maciej Miechowicz
 */
public class PlayerServiceImpl extends AbstractService implements PlayerService {

    private static final LoggerWrapper logger = 
    	new LoggerWrapper(Logger.getLogger("com.aceitunaproject.player"));

    /**
	 * Creates a new instance of the service
	 * 
	 * @param properties application properties
	 * @param systemRegistry component registry
	 * @param txnProxy transaction proxy
	 */
	public PlayerServiceImpl(
			Properties properties,
			ComponentRegistry systemRegistry,
			TransactionProxy txnProxy)
	{
		super(properties, systemRegistry, txnProxy, logger);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public Player getPlayer(ClientSession playerSession) {
        if(playerSession == null)
        	throw new NullPointerException("Null session");
		
		DataManager dataManager = AppContext.getDataManager();

		// TODO: add identity retrieval to obtain more detailed
		// info about the player
		String name = playerSession.getName();
		
        // try to get a player instance
        Player player = null;
        try {
            player = (Player) dataManager.getBinding(PLAYER_PREFIX + name);
        } catch (NameNotBoundException e) {
            player = new Player(name);
            dataManager.setBinding(PLAYER_PREFIX + name, player);
        }

        return player;
	}

	/**
	 * Handles service startup
	 */
	@Override
	protected void doReady() {
	}

	/**
	 * Handles service shutdown
	 */
	@Override
	protected void doShutdown() {
	}

	/**
	 * Handles service version mismatch
	 * 
	 * @param oldVersion old version
	 * @param currentVersion current version
	 */
	@Override
	protected void handleServiceVersionMismatch(Version oldVersion, Version currentVersion) {
		throw new UnsupportedOperationException("Unsupported operation");
	}

}
